package com.openvalley.cyj.synergy.slice;

import com.openvalley.cyj.synergy.ResourceTable;
import com.openvalley.cyj.synergy.pojo.MyRemoteProxy;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.ability.IAbilityContinuation;
import ohos.aafwk.ability.continuation.*;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Text;
import ohos.bundle.ElementName;
import ohos.distributedschedule.interwork.DeviceManager;
import ohos.distributedschedule.interwork.IInitCallback;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.IRemoteObject;
import ohos.rpc.RemoteException;

public class MainAbilitySlice extends AbilitySlice implements IAbilityContinuation {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0x00001, MainAbilitySlice.class.getSimpleName());

    Text text_register = null;
    Text text_show = null;
    Text text_startSynergy = null;
    Text text_stopSynergy = null;
    Text text_connectSynergy = null;
    Text text_operateSynergy = null;
    Text text_disconnectSynergy = null;

    IContinuationRegisterManager continuationRegisterManager = null;
    IContinuationDeviceCallback continuationDeviceCallback = null;
    RequestCallback requestCallback = null;
    IInitCallback initCallback = null;
    IAbilityConnection abilityConnection = null;

    String jsonParams = null;
    int abilityToken = 0;
    String deviceId = null;

    MyRemoteProxy remoteProxy = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        initContinuationRegisterManager();
        initComponent();
    }

    /**
     * 初始化注册管理类
     */
    private void initContinuationRegisterManager(){
        continuationRegisterManager = getContinuationRegisterManager();
        //设备的回调（是在列出了设备列表后，选择某个设备进行流转连接成功或者断开时调用）
        continuationDeviceCallback = new IContinuationDeviceCallback() {
            @Override
            public void onConnected(ContinuationDeviceInfo deviceInfo) {
                try {
                    HiLog.info(LABEL_LOG, "onConnected()");
                    deviceId = deviceInfo.getDeviceId();
                    HiLog.info(LABEL_LOG, "onConnected() 连接成功。 deviceId = " + deviceId);
                    //多端协同需要初始化分布式环境
                    DeviceManager.initDistributedEnvironment(deviceId, initCallback);
                    continuationRegisterManager.updateConnectStatus(abilityToken, deviceId, DeviceConnectState.CONNECTED.getState(), requestCallback);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onDeviceConnectDone(String s, String s1) {
                HiLog.info(LABEL_LOG, "onDeviceConnectDone()");
            }

            @Override
            public void onDisconnected(String deviceId) {
                HiLog.info(LABEL_LOG, "onDisconnected()");
            }

            @Override
            public void onDeviceDisconnectDone(String s) {
                HiLog.info(LABEL_LOG, "onDeviceDisconnectDone()");
            }
        };
        //请求的回调（注册到服务中心成功）
        requestCallback = new RequestCallback() {
            @Override
            public void onResult(int i) {
                if(i > 0){
                    //为了保证更新数据时这个值还在，所以在if里写
                    abilityToken = i;
                    HiLog.info(LABEL_LOG, "onResult() 注册成功。 abilityToken = " + abilityToken);
                }else {
                    HiLog.info(LABEL_LOG, "onResult() 其他操作。 abilityToken = " + i);
                }
            }
        };
        //初始化的回调
        initCallback = new IInitCallback() {
            @Override
            public void onInitSuccess(String s) {
                HiLog.info(LABEL_LOG, "onInitSuccess() 初始化分布式环境成功 deviceId = " + s);
            }

            @Override
            public void onInitFailure(String s, int i) {
                HiLog.info(LABEL_LOG, "onInitSuccess() 初始化分布式环境成功 deviceId = " + s + " i = " + i);
            }
        };

        //服务连接的回调
        abilityConnection = new IAbilityConnection() {
            @Override
            public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int i) {
                HiLog.info(LABEL_LOG, "onAbilityConnectDone() 服务连接成功。");
                //初始化本地代理
                remoteProxy = new MyRemoteProxy(iRemoteObject);
            }

            @Override
            public void onAbilityDisconnectDone(ElementName elementName, int i) {
                HiLog.info(LABEL_LOG, "onAbilityDisconnectDone() 服务断开连接。");
            }
        };
    }

    /**
     * 初始化组件
     */
    private void initComponent(){
        text_register = (Text)findComponentById(ResourceTable.Id_text_register);
        text_register.setClickedListener(listen -> register());

        text_show = (Text)findComponentById(ResourceTable.Id_text_show);
        text_show.setClickedListener(listen -> show());

        text_startSynergy = (Text)findComponentById(ResourceTable.Id_text_startSynergy);
        text_startSynergy.setClickedListener(listen -> startSynergy());

        text_stopSynergy = (Text)findComponentById(ResourceTable.Id_text_stopSynergy);
        text_stopSynergy.setClickedListener(listen -> stopSynergy());

        text_connectSynergy = (Text)findComponentById(ResourceTable.Id_text_connectSynergy);
        text_connectSynergy.setClickedListener(listen -> connectSynergy());

        text_operateSynergy = (Text)findComponentById(ResourceTable.Id_text_operateSynergy);
        text_operateSynergy.setClickedListener(listen -> operateSynergy());

        text_disconnectSynergy = (Text)findComponentById(ResourceTable.Id_text_disconnectSynergy);
        text_disconnectSynergy.setClickedListener(listen -> disconnectSynergy());
    }

    /**
     * 点击按钮进行流转服务注册
     */
    private void register(){
        if(continuationRegisterManager != null){
            HiLog.info(LABEL_LOG, "register() 开始注册。");
            continuationRegisterManager.register(getBundleName(), getExtraParams(), continuationDeviceCallback, requestCallback);
        }
    }

    /**
     * 展示可流转的设备
     */
    private void show(){
        if(continuationRegisterManager != null && abilityToken > 0){
            continuationRegisterManager.showDeviceList(abilityToken, getExtraParams(), requestCallback);
        }
    }

    /**
     * 启动远端程序（FA/PA）
     */
    private void startSynergy(){
        Intent startIntent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId(deviceId)
                .withBundleName("com.chenyijie")
//                .withAbilityName("com.chenyijie.MainAbility")
                .withAbilityName("com.chenyijie.ServiceAbility")
                //开启分布式任务标记
                .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                .build();
        startIntent.setOperation(operation);
        startAbility(startIntent);
    }

    /**
     * 停止远端程序（PA）
     */
    private void stopSynergy(){
        //无法停止页面
        Intent stopIntent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId(deviceId)
                .withBundleName("com.chenyijie")
                .withAbilityName("com.chenyijie.ServiceAbility")
                //开启分布式任务标记
                .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                .build();
        stopIntent.setOperation(operation);
        stopAbility(stopIntent);
    }

    /**
     * 连接远端服务（PA）
     */
    private void connectSynergy(){
        Intent connectIntent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId(deviceId)
                .withBundleName("com.chenyijie")
                .withAbilityName("com.chenyijie.ServiceAbility")
                //开启分布式任务标记
                .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                .build();
        connectIntent.setOperation(operation);
        boolean connectAbility = connectAbility(connectIntent, abilityConnection);
        HiLog.info(LABEL_LOG, "connectSynergy() connectAbility = " + connectAbility);
    }

    /**
     * 操作远端服务（PA）
     */
    private void operateSynergy(){
        try {
            int addResult = remoteProxy.add(1, 2);
            HiLog.info(LABEL_LOG, "operateSynergy() addResult = " + addResult);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 断开远端服务（PA）
     */
    private void disconnectSynergy(){
        disconnectAbility(abilityConnection);
    }

    /**
     * 获得注册时 额外的一些参数
     * @return
     */
    private ExtraParams getExtraParams(){
        ExtraParams extraParams = new ExtraParams();
        String[] devType = {ExtraParams.DEVICETYPE_SMART_PHONE, ExtraParams.DEVICETYPE_SMART_PAD};
        //显示的列表包含那些设备类型
        extraParams.setDevType(devType);
        //添加描述（没出来）
        extraParams.setDescription("这是一个描述。");
        //如果不写，就会默认以注册时的BundleName作为targetBundleName
        extraParams.setTargetBundleName(getBundleName());
        //设备过滤
        jsonParams = "\"{" +
                "\"filter\":{" +
                "\"commonFilter\":{" +
                "\"system\":{" +
                //目标设备对应的HarmonyOS版本 要≥
                "\"harmonyVersion\":\"2.0.0\"" +
                "}," +
//                                "}" +
                //1为同账号，1|256为不同账号
                "\"groupType\":\"1|256\"," +
                //0x00000004需要在同一局域网下，0x00030004不需要在同一局域网下
                "\"curComType\": 0x00030004," +
                //为空就不做版本兼容性检查，要做版本兼容性检查时，需要传入目标应用包名。
                "\"faFilter\":\"{" +
                "\"targetBundleName\":\"com.openvalley.cyj.migration\"" +
                "}\"" +
                "}" +
                "}," +
                "\"transferScene\":0," +
                "\"remoteAuthenticationDescription\": \"拉起HiVision扫描弹框描述\"" +
                "}\"";
//        HiLog.info(LABEL_LOG, jsonParams);
        extraParams.setJsonParams(jsonParams);
        return extraParams;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        if(continuationRegisterManager != null && abilityToken > 0){
            continuationRegisterManager.unregister(abilityToken, requestCallback);
        }
        //断开流转任务管理服务连接
        continuationRegisterManager.disconnect();
    }

    /**
     * 准备开始迁移的回调
     * @return
     */
    @Override
    public boolean onStartContinuation() {
        //返回值为true才发起迁移
        HiLog.info(LABEL_LOG, "MainAbilitySlice onStartContinuation");
        return true;
    }

    /**
     * 当保存数据（要迁移的数据）的回调
     * @param intentParams
     * @return
     */
    @Override
    public boolean onSaveData(IntentParams intentParams) {
        HiLog.info(LABEL_LOG, "MainAbilitySlice onSaveData");
        return true;
    }

    /**
     * 当恢复数据的回调（应该是被迁移的设备调用
     * @param intentParams
     * @return
     */
    @Override
    public boolean onRestoreData(IntentParams intentParams) {
        //返回为true代表恢复数据成功
        HiLog.info(LABEL_LOG, "MainAbilitySlice onRestoreData");
        return true;
    }

    /**
     * 迁移完成的回调
     * @param i
     */
    @Override
    public void onCompleteContinuation(int i) {
        HiLog.info(LABEL_LOG, "MainAbilitySlice onCompleteContinuation");
    }

    /**
     * 迁移过程中失败的回调
     */
    @Override
    public void onRemoteTerminated() {
        HiLog.info(LABEL_LOG, "MainAbilitySlice onRemoteTerminated");
    }

    /**
     * 回迁允许的情况下，远端中断
     * @param errorCode
     */
    @Override
    public void onFailedContinuation(int errorCode) {
        IAbilityContinuation.super.onFailedContinuation(errorCode);
        HiLog.info(LABEL_LOG, "MainAbilitySlice onFailedContinuation");
    }
}
